<?php
/**
 * Created by PhpStorm.
 * User: jocky
 * Date: 2017/6/6
 * Time: 上午10:26
 */

namespace common\behaviors;

use common\models\ar\MustBeDoneLists;
use yii\base\ActionFilter;

class MustBeDoneBehavior extends ActionFilter
{
    public $userType = 1;//1代理，2交易客户

    /**
     * 必填项检测，如：免责声明和风险问卷等
     *
     * @param \yii\base\Action $action
     * @return bool
     */
    public function beforeAction($action)
    {
        //允许没有登录的操作，不需要执行以下验证，直接返回true
        if (\Yii::$app->user->isGuest) {
            return true;
        }

        $uid = \Yii::$app->user->identity->uid;
        //1：免责申明检测
        if ($action->id != "disclaimer" && !$this->check($uid, 2)) {
            //不在免责声明页，并且没有同意，需要跳到声明页
            if (\Yii::$app->request->isAjax) {
                exit(json_encode([101, '请认真阅读并同意《免责申明》', ['url' => '/interface/disclaimer']]));
            } else {
                \Yii::$app->response->redirect('/interface/disclaimer');
                return false;
            }
        } else {
            //如果当前是免责声明页，并且已经同意，则跳到主页
            if ($action->id == "disclaimer" && $this->check($uid, 2)) {
                \Yii::$app->response->redirect(\Yii::$app->homeUrl);
                return false;
            }
        }

        if ($this->userType == 1) {
            //2：风险问卷检测，必须先同意风险声明
            if ($this->check($uid, 2)) {
                if ($action->id != "risk-questions" && !$this->check($uid, 3)) {
                    //不在免责声明页，并且没有同意，需要跳到声明页
                    if (\Yii::$app->request->isAjax) {
                        exit(json_encode([101, '请认真回答风险问题', ['url' => '/interface/risk-questions']]));
                    } else {
                        \Yii::$app->response->redirect('/interface/risk-questions');
                        return false;
                    }
                } else {
                    //如果当前是风险问卷调查页，并且已经回答，则跳到主页
                    if ($action->id == "risk-questions" && $this->check($uid, 3)) {
                        \Yii::$app->response->redirect(\Yii::$app->homeUrl);
                        return false;
                    }
                }
            }
        }

        return parent::beforeAction($action);
    }

    /**
     * 必须完成的事项检测
     *
     * @param $uid
     * @param $type
     * @param bool $detail
     * @return bool|int|string|\yii\db\ActiveRecord
     */
    public function check($uid, $type, $detail = false)
    {
        $res = MustBeDoneLists::find()->where(['uid' => $uid, 'type' => $type]);
        if (!$count = $res->count()) {
            return false;
        }

        if (!$detail) {
            return $count;
        } else {
            return $res->asArray()->all()[0];
        }
    }
}
